from fastapi import APIRouter, Depends, status, Response
from db import get_db, crud
from schemas.flower import FlowerTypeModel, CreateFlowerTypeRequest, UpdateFlowerTypeRequest, FlowerTypePagination
from users.users import verify_token
from utils.response import HTTPException
from sqlalchemy.orm import Session
from datetime import datetime
from loguru import logger
from typing import Optional, List

router = APIRouter(prefix="/flower/type", tags=["鲜花分类"])


@router.post("",
             dependencies=[Depends(verify_token)],
             response_model=FlowerTypeModel,
             response_model_exclude_none=True)
def create(data: CreateFlowerTypeRequest, db: Session = Depends(get_db)):
    if crud.FlowerType.get_by_name(db, data.name) is None:
        data.created_on = datetime.now()
        return crud.FlowerType.create(db, data)
    else:
        raise HTTPException(message="已存在相同名称的分类")


@router.get("",
            dependencies=[Depends(verify_token)],
            response_model=FlowerTypePagination,
            response_model_exclude_none=True)
def get_flower_type_pagination(page: int, page_size: int, kw: Optional[str] = None, db: Session = Depends(get_db)):
    try:
        total, data = crud.FlowerType.gets(db, page - 1, page_size, kw)

        type_list = []

        for i in data:
            item = FlowerTypeModel.from_orm(i)
            item.count = crud.Flower.count_by_type(db, item.id)
            type_list.append(item)

        return FlowerTypePagination(
            page=page,
            page_size=page_size,
            total=total,
            data=type_list
        )
    except Exception as err:
        logger.error(str(err))
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)


@router.get("/items", dependencies=[Depends(verify_token)])
def get_flower_type_items(db: Session = Depends(get_db)):
    items = crud.FlowerType.get_items(db)
    return [{
        "id": i.id,
        "name": i.name
    } for i in items]


@router.get("/all", response_model=List[FlowerTypeModel], response_model_exclude_none=True)
def get_all(db: Session = Depends(get_db)):
    return crud.FlowerType.get_all(db)


@router.put("", dependencies=[Depends(verify_token)], response_model_exclude_none=True)
def update(data: UpdateFlowerTypeRequest, db: Session = Depends(get_db)):
    old = crud.FlowerType.get_by_name(db, data.name)
    if old is None or old.id != data.id:
        data.updated_on = datetime.now()
        crud.FlowerType.update(db, data)

        return Response()
    else:
        raise HTTPException(message="已存在相同名称的分类")


@router.delete("/{item_id}", dependencies=[Depends(verify_token)], response_model_exclude_none=True)
def delete(item_id: int, db: Session = Depends(get_db)):
    crud.FlowerType.delete(db, item_id)
    return Response()
